import React, { useState, useEffect, useRef } from 'react';
import ContentTop from '../../../components/ContentTop';
import { Button, Table, Switch, Input, Modal, Form, Radio, message } from 'antd';
import { cateList, editCate, cateDelete, addCate } from "../../../api/account";

export default function GoodsType() {
    const formRef = useRef()
    const [deleteRecord, setDeleteRecord] = useState(null);
    const [editingKey, setEditingKey] = useState(null);
    const [editRecord, setEditRecord] = useState(null);
    const [typeList, setTypeList] = useState([]);
    const [pagination, setPagination] = useState({ current: 1, pageSize: 5 });
    const [inputValue, setInputValue] = useState('');
    const [stateValue, setStateValue] = useState(0);
    const [switchState, setSwitchState] = useState(0);
    const [open, setOpen] = useState(false);
    const hideModal = () => {
        setOpen(false);
    };


    const columns = [
        {
            title: '序号',
            dataIndex: 'id',
        },
        {
            title: '分类名',
            dataIndex: 'cateName',
            render: (text, record) => {
                const isEditing = record.id === editingKey;
                return isEditing ? (
                    <Input
                        name='cateName'
                        defaultValue={text}
                        onChange={handleInputChange}
                    />
                ) : (
                    text
                );
            },
        },
        {
            title: '是否启用',
            dataIndex: 'state',
            render: (state, record) => {
                return (
                    <Switch
                        checked={state === 1}
                        disabled={switchState != 1}
                        onChange={(checked) => handleStateChange(checked, record)}
                    />
                );
            },
        },
        {
            title: '操作',
            dataIndex: 'active',
            render: (_, record) => {
                const isEditing = record.id === editingKey;
                return (
                    <span>
                        {isEditing ? (
                            <Button
                                type="primary"
                                onClick={() => handleSave()}
                            >
                                完成
                            </Button>
                        ) : (
                            <Button
                                onClick={() => handleEdit(record)}
                            >
                                编辑
                            </Button>
                        )}
                        <Button
                            type="primary"
                            danger
                            style={{ marginLeft: 10 }}
                            onClick={() => {
                                setDeleteRecord(record);
                            }}
                        >
                            删除
                        </Button>
                    </span>
                );
            },
        },
    ];

    const handleDelete = async () => {
        if (deleteRecord) {
            let res = await cateDelete({ id: deleteRecord.id });
            if(res.data.code == 0){
                setDeleteRecord(null);
                fetchData(pagination.current, pagination.pageSize);
                message.success(res.data.msg);
            }else{
                message.error(res.data.msg);
            }

        }
    };

    const handleTableChange = (newPagination) => {
        setPagination(newPagination);
        fetchData(newPagination.current, newPagination.pageSize);
    };

    const fetchData = async (currentPage, pageSize) => {
        const res = await cateList({ currentPage, pageSize });
        setTypeList(res.data.data);
        setPagination((prevPagination) => ({
            ...prevPagination,
            total: res.data.total,
            pageSize,
        }));
    };

    useEffect(() => {
        fetchData(pagination.current, pagination.pageSize);
    }, []);

    const data = typeList.map((item) => ({
        id: item.id,
        cateName: item.cateName,
        state: item.state,
    }));

    // **********************************************//
    const handleInputChange = (e) => {
        setInputValue(e.target.value);
    };

    const handleEdit = (record) => {
        setStateValue(record.state === 1 ? 1 : 0);
        setSwitchState(1);
        setEditingKey(record.id);
        setEditRecord(record);
    };

    const handleStateChange = async (checked, record) => {
        setStateValue(checked ? 1 : 0);
        const updatedRecord = { ...record, state: checked ? 1 : 0 };
        await editCate(updatedRecord);
        const updatedTypeList = typeList.map(item => {
            if (item.id === record.id) {
                return { ...item, state: checked ? 1 : 0 };
            } else {
                return item;
            }
        });
        setTypeList(updatedTypeList);
    };


    const handleSave = async () => {
        setSwitchState(0);
        const values = {
            id: editRecord.id,
            cateName: inputValue ? inputValue : editRecord.cateName,
            state: stateValue,
        };
        let res = await editCate(values);
        if (res.data.code == 0) {
            message.success(res.data.msg);
            setEditingKey(null);
            setEditRecord(null);
            fetchData(pagination.current, pagination.pageSize);
        } else {
            message.error(res.data.msg);
        }

    };

    const handleAdd = () => {
        setOpen(true);
    }

    const handleAddSubmit = async () => {
        const data = formRef.current.getFieldsValue();
        let res = await addCate(data);
        if (res.data.code == 0) {
            message.success(res.data.msg);
            setOpen(false);
            fetchData(pagination.current, pagination.pageSize);
        } else {
            message.error(res.data.msg);
        }

    }

    const [value, setValue] = useState(1);
    const onChange = (e) => {
        setValue(e.target.value);
    };

    return (
        <>
            <div className="app-content">
                <ContentTop>
                    <div className="title">商品分类</div>
                    <div className="btn">
                        <Button onClick={() => handleAdd()}>添加分类</Button>
                    </div>
                </ContentTop>
                <div className="content-info">
                    <Table
                        columns={columns}
                        dataSource={data} bordered
                        tableLayout='fixed'
                        style={{ width: '100%' }}
                        pagination={pagination}
                        onChange={handleTableChange}
                    />
                </div>
                <Modal
                    title="添加分类"
                    onCancel={hideModal}
                    onOk={handleAddSubmit}
                    open={open}
                >
                    <Form
                        ref={formRef}
                    >
                        <Form.Item label="分类名" name="cateName">
                            <Input />
                        </Form.Item>
                        <Form.Item label="状态" name="state" >
                            <Radio.Group onChange={onChange} value={value}>
                                <Radio value={1}>启用</Radio>
                                <Radio value={0}>禁用</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </Form>
                </Modal>

                <Modal
                    title="确认删除"
                    visible={!!deleteRecord}
                    onOk={handleDelete}
                    onCancel={() => setDeleteRecord(null)}
                >
                    <p>您确定要删除这个分类吗？</p>
                </Modal>
            </div>
        </>
    );
}
